<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { useForm, useFormRules } from '@/hooks/common/form';
import { $t } from '@/locales';
import { fetchGetUserPostList, fetchUserInfoSave } from '@/service/api';
import { useLoading } from '~/packages/hooks';
import { Sex } from '@/constants/custom';

type Model = Api.System.User.UserInfoFormModel;

defineOptions({ name: 'UserFormDrawer' });

interface Props {
  deptId?: CommonType.IdType;
  operateType: UI.TableOperateType;
  rowData?: Api.System.User.UserInfoRecord | null;
  maxOrderNum?: number;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const { formRef, validate, restoreValidation } = useForm();
const { createRequiredRule, patternRules } = useFormRules();

function createDefaultModel(): Model {
  return {
    id: '',
    username: '',
    nickname: '',
    fullname: '',
    sex: 'UNKNOWN',
    mobile: '',
    idCode: '',
    email: '',
    address: '',
    avatar: '',
    post: '',
    deptId: props.deptId || '0', // deptId <=0 独立用户
    enabled: 1,
    orderNum: (props.maxOrderNum || 0) + 10
  };
}

const model = ref<Model>(createDefaultModel());

type RuleKey = Extract<Model, 'username' | 'mobile' | 'email' | 'enabled'>;
const rules = ref<Record<RuleKey, App.Global.FormRule>>({
  username: createRequiredRule($t('form.required')),
  mobile: patternRules.phone,
  email: patternRules.email,
  enabled: createRequiredRule($t('form.enabled'))
});

const visible = defineModel<boolean>('visible', {
  default: false
});
const title = computed(() => {
  const titles: Record<UI.TableOperateType, string> = {
    add: '新增用户',
    edit: '编辑用户'
  };
  return titles[props.operateType];
});

function handleInitModel() {
  model.value = createDefaultModel();

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model.value, props.rowData);
  }
}

function closeDrawer() {
  visible.value = false;
}

const { loading, startLoading, endLoading } = useLoading(false);

async function handleSubmit() {
  try {
    await validate();
    startLoading();
    // request
    const { error } = await fetchUserInfoSave(model.value);
    // success
    if (error) return;
    window.$message?.success($t('common.updateSuccess'));
    closeDrawer();
    emit('submitted');
  } finally {
    endLoading();
  }
}

// 用户岗位列表
const userPostList = ref<Api.System.User.UserPostRecord[]>();

// 获取部门类型
async function getUserPostList() {
  const { data, error } = await fetchGetUserPostList();
  if (error) return;
  userPostList.value = data;
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getUserPostList();
  }
});
</script>

<template>
  <ElDrawer v-model="visible" :title="title" :close-on-click-modal="false" direction="rtl" size="850">
    <ElForm ref="formRef" :model="model" :rules="rules" label-position="top">
      <ElRow :gutter="15">
        <ElCol :span="12">
          <ElFormItem label="用户名" prop="username">
            <ElInput v-model="model.username" placeholder="用户名" maxlength="100" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="用户昵称" prop="nickname">
            <ElInput v-model="model.nickname" placeholder="用户昵称" maxlength="100" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="用户姓名" prop="fullname">
            <ElInput v-model="model.fullname" placeholder="用户姓名" maxlength="100" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="用户性别" prop="sex">
            <ElRadioGroup v-model="model.sex">
              <template v-for="item in Object.keys(Sex)" :key="item">
                <ElRadio :value="item" :label="Sex[item]" />
              </template>
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="手机号码" prop="mobile">
            <ElInput v-model="model.mobile" placeholder="手机号码" maxlength="11" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="证件号码" prop="idCode">
            <ElInput v-model="model.idCode" placeholder="证件号码" maxlength="50" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="邮箱地址" prop="email">
            <ElInput v-model="model.email" placeholder="邮箱地址" maxlength="100" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="联系地址" prop="address">
            <ElInput v-model="model.address" placeholder="联系地址" maxlength="200" show-word-limit />
          </ElFormItem>
        </ElCol>
        <ElCol v-if="Number(model.deptId || 0) > 0" :span="12">
          <ElFormItem label="用户岗位" prop="post">
            <ElSelect v-model="model.post" placeholder="用户岗位">
              <ElOption v-for="item in userPostList" :key="item.id" :value="item.code" :label="item.name" />
            </ElSelect>
          </ElFormItem>
        </ElCol>
        <ElCol v-if="Number(model.deptId || 0) > 0" :span="12">
          <ElFormItem :label="$t('form.orderNum')" prop="orderNum">
            <ElInputNumber
              v-model="model.orderNum"
              :placeholder="$t('form.orderNum')"
              :step="10"
              controls-position="right"
              :precision="0"
              class="wfull"
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem label="过期时间" prop="expiredTime">
            <ElDatePicker
              v-model="model.expiredTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="过期时间"
              clearable
            />
          </ElFormItem>
        </ElCol>
        <ElCol :span="12">
          <ElFormItem :label="$t('form.enabled')" prop="enabled">
            <ElRadioGroup v-model="model.enabled">
              <ElRadio :label="$t('form.enabledOptions.enabled')" :value="1" />
              <ElRadio :label="$t('form.enabledOptions.disabled')" :value="0" />
            </ElRadioGroup>
          </ElFormItem>
        </ElCol>
        <ElCol :span="24">
          <ElFormItem label="备注" prop="remark">
            <ElInput v-model="model.remark" type="textarea" placeholder="备注" maxlength="500" show-word-limit />
          </ElFormItem>
        </ElCol>
      </ElRow>
    </ElForm>
    <template #footer>
      <ElSpace v-loading="loading" :size="16">
        <ElButton @click="closeDrawer">{{ $t('common.cancel') }}</ElButton>
        <ElButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</ElButton>
      </ElSpace>
    </template>
  </ElDrawer>
</template>

<style scoped>
:deep(.el-input-number .el-input__inner) {
  text-align: left;
}

:deep(.el-input) {
  width: 100%;
}
</style>
